<template>
  <el-card class="box-card">
    <div class="role">
       <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
       <br>
      <el-button class="rol_btn" type="info" @click="dialogVisibleclick()"
        >添加</el-button
      >

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <div v-if="props.row.children.length != 0">
              <el-tree-v2 :data="props.row.children" :props="propsOne"></el-tree-v2>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="序号" />
        <el-table-column prop="roleName" label="角色名" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              @click="dialogVisibleclick(scope.row)"
              :icon="Edit"
            ></el-button>
            <el-button
              type="primary"
              @click="deteleUser(scope.row.id)"
              :icon="Delete"
            ></el-button>
            <el-button
              type="primary"
              @click="updateRole(scope.row.id)"
              :icon="Tools"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="page">
                <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.pageNo"
            :page-sizes="[5,10,15]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="num">
    </el-pagination>
      </div>

      <el-dialog v-model="dialogrole" width="30%">
        <span>角色名:</span>
        <el-input v-model="roleU"></el-input>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogrole = false">取消</el-button>
            <el-button type="primary" @click="dialogRoleupadte()">确认</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="dialogsan" title="删除" width="30%">
        <span>是否确认删除</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="delteroleId()">确认</el-button>
            <el-button type="primary" @click="dialogsan = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <el-dialog v-model="dialoEdite" width="30%">
      <el-tree
        :props="props"
        :data="dataRole"
        show-checkbox
        @check="handleCheckChange"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialoEdite = false">取消</el-button>
          <el-button type="primary" @click="dialogEidetupadte()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import {
  defineComponent,
  onMounted,
  getCurrentInstance,
  reactive,
  toRefs,
  ref,
  toRaw,
  watch,
} from "vue";
import { Edit, Share, Delete, Search, Upload, Tools } from "@element-plus/icons-vue";
// import { request } from '../service'
import httpRequest from '../service';


import type Node from "element-plus/es/components/tree/src/model/node";
import { ElMessage, ElMessageBox } from "element-plus";

const expanedKeys: string[] = [];
const tableData = ref([]);
const dialogrole = ref(false);
const dialogsan = ref(false);
const roleId = ref("");
const roleU = ref("");
const rolesdId = ref(0);
let num = ref<Number>(0);
const dialoEdite = ref(false);
const roleUserId = ref("");
const page = reactive({
  pageNo: 1,
  pageSize: 20,
});

interface Tree {
  id: string;
  label: string;
  children?: Tree[];
}
const props = {
  value: "id",
  label: "menuname",
  children: "children",
};
const treeOne = ref();
let roleAdd:any[] = [];
let roleIds = "";
// 修改权限（节点操作）
const handleCheckChange = (keys:any,nodes:any) => {
  let { checkedNodes } = nodes
  let arr:any[] = []
  checkedNodes.forEach((element:any) => {
    arr.push(element.id)
    if(element.parentid!=0){
      arr.push(element.parentid)
    }
  });
  roleIds = Array.from(new Set(arr)).join("_");
};

const getKey = (prefix: string, id: number) => {
  return `${prefix}-${id}`;
};
const dataQueRole = ref([]);
const dataRole = ref([]);
const propsOne = {
  value: "id",
  label: "menuname",
  children: "children",
};

onMounted(() => {
  getRoes();
});

// 修改权限分配(1.1)
const updateRole = (id:any) => {
  roleUserId.value = id;

  let ssas = [];
  httpRequest.request({ url: "/menu/listmenu", method: 'post' }).then((res: any) => {
    let op = res.data;
    console.log(res);
    
    dataRole.value = op;
    for (let i = 0; i < op.length; ++i) {
      expanedKeys.push(op[i].id);
    }
  });
  dialoEdite.value = true;
};


// 修改权限分配(1.3)
const dialogEidetupadte =async () => {
  // console.log(roleUserId._rawValue,roleIds);
  await httpRequest.request({
    url: "/roles_and_menu/addroles_and_menu",
    data: { roleid: roleUserId.value, idstr: roleIds },
    method: 'post'
  })
  getRoes()
    dialoEdite.value = false;
    ElMessage({
      message: "修改成功",
      type: "success",
    });

};

const delteroleId = () => {
  httpRequest.request({ url: "/roles/delroles", data: { id: roleId.value }, method: 'post' }).then(
    (res: any) => {
      dialogsan.value = false;
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getRoes();
    }
  );
};

// 删除
const deteleUser = (Id:any) => {
  dialogsan.value = true;
  roleId.value = Id;
};

const dialogVisibleclick = (userdetail:any) => {
  if (userdetail == undefined) {
    roleU.value = "";
  } else {
    let sds = { ...userdetail };
    roleU.value = sds.roleName;
    rolesdId.value = sds.id;
  }
  dialogrole.value = true;
};

const dialogRoleupadte =async () => {
  if (rolesdId.value == 0) {
    await httpRequest.request({
      url: "/roles/addroles",
      data: { roleName: roleU.value },
    })
  } else {
    await httpRequest.request({
      url: "/roles/updroles",
      data: { id: rolesdId.value, roleName: roleU.value },
      method: 'post'
    })
  }
  dialogrole.value = false;
  getRoes();
};

const handleSizeChange = (pageSize: number | string) => {
  page.pageNo = 1;
  page.pageSize = Number(pageSize);
  getRoes();
};
const handleCurrentChange = () => {
  getRoes();
};

const getRoes =  () => {
  // let {
  //     data: { count, rows },
  //   } = await 
    httpRequest.request({ url: "/roles/listroles", data: page, method: 'post' }).then((rs:any)=>{
      num.value=rs.data.count
        tableData.value =rs.data.rows;
    })
    // console.log(res.data);
  
};
</script>

<style lang="less" scoped>
.box-card {
  width: 85vw;
}

.rol_btn {
  float: left;
  margin-bottom: 20px;
}

</style>
